<?php

namespace app\common\model;

use think\Model;


class Goods extends Model
{





    // 表名
    protected $name = 'goods';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'recommend_text',
        'status_text',
        'spec_image',
        'goods_images'
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });
    }


    public function getRecommendList()
    {
        return ['1' => __('Recommend 1'), '2' => __('Recommend 2')];
    }

    public function getStatusList()
    {
        return ['1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getRecommendTextAttr($value, $data)
    {
        $value = $value ?: ($data['recommend'] ?? '');
        $list = $this->getRecommendList();
        return $list[$value] ?? '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }




    public function typeone()
    {
        return $this->belongsTo('Typeone', 'one_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function typetwo()
    {
        return $this->belongsTo('Typetwo', 'two_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function brand()
    {
        return $this->belongsTo('Brand', 'brand_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getGoodsImageAttr($value, $data)
    {
        // 为image拼接域名
        $value = cdnurl($value, true);
        return $value;
    }

    public function setGoodsImageAttr($value, $data)
    {
        // 去掉image域名
        $value = parse_url($value)['path'];
        return $value;
    }

    public function getSpecImageAttr($value, $data)
    {
        if (!empty($data['spec'])) {
            // 循环查询结果
            $spec_data = json_decode($data['spec'], true);
            foreach ($spec_data as $key1 => &$value1) {
                // 为image拼接域名
                $value1["image"] = cdnurl($value1["image"], true);
            }
            return $spec_data;
        }
    }

    public function getGoodsImagesAttr($value, $data)
    {
        if (!empty($data['goods_images'])) {
            // 循环查询结果
            $goods_images_data = explode(",", $data['goods_images']);
            foreach ($goods_images_data as $key => &$value) {
                // 为image拼接域名
                $value = cdnurl($value, true);
            }
            return $goods_images_data;
        }
    }
}
